package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;

    // Spring提供的匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //  1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())){
            // 放行
            return chain.filter(exchange);
        }
        //  3.获取token
        String token = null;
        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("authorization");
        if (authorization != null && !headers.isEmpty()){
            token = authorization.get(0);
        }


        // 4.校验并解析token
        Long userId = null;
        try {
            // 希望解析失败终止请求，而不是抛出异常，所以try catch （彰显出是登录失败被拦截，使用HTTP状态码401表示）
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 终止执行
        }


        // 5.传递用户信息
        log.info("userId: {}",userId); // 网关传递用户信息到请求头
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate() // 修改请求
                .request(builder -> builder.header("user-info", userInfo)) // 增加一个请求头，把用户加进去
                .build(); // 网关转发请求到微服务时，就携带用户信息了。

        //  6.放行

        return chain.filter(swe);
    }

    // 判断当前路径是否需要放行
    private boolean isExclude(String path) {
        for (String excludePattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePattern,path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
